package com.scs.application.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.utils.PinYinUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UtilCommon;
import com.scs.application.modules.base.entity.*;
import com.scs.application.modules.base.service.*;
import com.scs.application.modules.base.util.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @description: 系统通用服务类
 **/
@Service
@Slf4j
public class SystemCommonServiceImpl {

    @Autowired
    private MatrService matrService;

    @Autowired
    private MatrHisService matrHisService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private MfgService mfgService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private DeptService deptService;

    /**
     * @description: 生成系统拼音检索码
     * 1、生成范围：商品主档、供应商、生产企业、仓库、科室
     * 2、拼音检索码字段为空的生成
     * 3、生成策略，名称首字母
     **/
    public String buildInfoMap() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.isNull("name_py");
        queryWrapper.select("id,name,name_py");

        List<String> msgList = new ArrayList<>();

        List<Matr> matrList =  matrService.list(queryWrapper);
        if (matrList.isEmpty()) {
            msgList.add("商品无须生成");
        } else{
            matrList.stream().forEach(item -> {
                matrService.update(
                        Wrappers.<Matr>update()
                                .eq("id",item.getId())
                                .set("name_py",UtilCommon.getStringPre(PinYinUtils.getAlpha(item.getName()), 50))
                );
            });
            msgList.add("商品检索码生成数量" + matrList.size());
        }

        List<Supplier> supplierList =  supplierService.list(queryWrapper);
        if (supplierList.isEmpty()) {
            msgList.add("供应商无须生成");
        } else{
            supplierList.stream().forEach(item -> {
                supplierService.update(
                        Wrappers.<Supplier>update()
                                .eq("id",item.getId())
                                .set("name_py",UtilCommon.getStringPre(PinYinUtils.getAlpha(item.getName()), 50))
                );
            });
            msgList.add("供应商检索码生成数量" + supplierList.size());
        }

        List<Mfg> mfgList =  mfgService.list(queryWrapper);
        if (mfgList.isEmpty()) {
            msgList.add("厂商无须生成");
        } else{
            mfgList.stream().forEach(item -> {
                mfgService.update(
                        Wrappers.<Mfg>update()
                                .eq("id",item.getId())
                                .set("name_py",UtilCommon.getStringPre(PinYinUtils.getAlpha(item.getName()), 50))
                );
            });
            msgList.add("厂商检索码生成数量" + mfgList.size());
        }

        List<Warehouse> warehouseList =  warehouseService.list(queryWrapper);
        if (warehouseList.isEmpty()) {
            msgList.add("仓库无须生成");
        } else{
            warehouseList.stream().forEach(item -> {
                warehouseService.update(
                        Wrappers.<Warehouse>update()
                                .eq("id",item.getId())
                                .set("name_py",UtilCommon.getStringPre(PinYinUtils.getAlpha(item.getName()), 50))
                );
            });
            msgList.add("仓库检索码生成数量" + warehouseList.size());
        }

        List<Dept> deptList =  deptService.list(queryWrapper);
        if (deptList.isEmpty()) {
            msgList.add("科室无须生成");
        } else{
            deptList.stream().forEach(item -> {
                deptService.update(
                        Wrappers.<Dept>update()
                                .eq("id",item.getId())
                                .set("name_py",UtilCommon.getStringPre(PinYinUtils.getAlpha(item.getName()), 50))
                );
            });

            msgList.add("科室检索码生成数量" + deptList.size());
            //院方科室
            CommonService.cacheDept();
        }


        msgList.add(buildMatrHisInfo());

        return StringUtils.join(msgList,",");
    }


    // 根据医保名称27位，修复商品的his收费编码信息
    public String buildMatrHisInfo() {
        List<Matr> matrList =  matrService.list(Wrappers.<Matr>query().isNotNull("his_medicare_no2").isNull("his_code"));
        if (matrList.isEmpty()) {
            return "商品HIS收费项目修复结果:没有可修复的商品数据";
        }
        // 根据医保编码分组
        Map<String,List<MatrHis>> matrHisGroupByNationalCode =  matrHisService.list(Wrappers.<MatrHis>query().isNotNull("his_code").isNotNull("national_code"))
                .stream().collect(Collectors.groupingBy(MatrHis::getNationalCode));
        if (matrList.isEmpty()) {
            return "商品HIS收费项目修复结果:没有可用的HIS收费项目";
        }
        AtomicReference<MatrHis> matrHisFind = new AtomicReference<>();
        int numUpdate = 0;
        for(Matr matr: matrList) {
            if (!matrHisGroupByNationalCode.containsKey(matr.getHisMedicareNo2())) {
                continue;
            }
            matrHisFind.set(null);
            if (matrHisGroupByNationalCode.get(matr.getHisMedicareNo2()).size() == 1) {
                matrHisFind.set(matrHisGroupByNationalCode.get(matr.getHisMedicareNo2()).get(0));
            } else{
                // 找非禁用的价格一致的
                matrHisGroupByNationalCode.get(matr.getHisMedicareNo2()).stream()
                        .filter(item -> !item.isFlagDisabled() && item.getPricePatientAdult() !=null &&  item.getPricePatientAdult().equals(matr.getSkuPrice()))
                        .findFirst().ifPresent(item -> {
                            matrHisFind.set(item);
                        });
                if (matrHisFind.get() == null) {
                    // 找所有的价格一致的
                    matrHisGroupByNationalCode.get(matr.getHisMedicareNo2()).stream()
                            .filter(item ->  item.getPricePatientAdult() !=null && item.getPricePatientAdult().equals(matr.getSkuPrice()))
                            .findFirst().ifPresent(item -> {
                                matrHisFind.set(item);
                            });
                }
            }
            if (matrHisFind.get() == null) {
                continue;
            }
            matrService.update(
                    Wrappers.<Matr>update()
                            .eq("id",matr.getId())
                            .set("his_code", matrHisFind.get().getHisCode())
                            .set("his_name", matrHisFind.get().getName())
                            .set("his_price", matrHisFind.get().getPricePatientAdult())
                            .set("his_disabled", matrHisFind.get().isFlagDisabled())
                            .set(StringUtils.isNotBlank(matrHisFind.get().getNationalName()),"his_medicare_name2", matrHisFind.get().getNationalName())
            );
            numUpdate++;
        }


        return "商品HIS收费项目修复结果:修复商品数量" + numUpdate;
    }
}
